package com.astuetz.autoplay;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * Created by zengxianming on 2017/1/12.
 * version 1.0
 */
public class CommonPageAdapter extends PagerAdapter {

    private final List<View> mViewList;
    private List<? extends CommonBannerHolder.IShowImgAble> imgUrlList;
    private Context mContext;

    public CommonPageAdapter(List<View> pages, Context cxt) {
        this(pages, cxt, null);
    }

    public CommonPageAdapter(List<View> pages, Context cxt, List<? extends CommonBannerHolder.IShowImgAble> imgUrlList) {
        mContext = cxt;
        this.mViewList = pages;
        this.imgUrlList = imgUrlList;
    }

    public void setImgUrlList(List<CommonBannerHolder.IShowImgAble> imgUrlList) {
        this.imgUrlList = imgUrlList;
    }

    public boolean addView(View v) {
        return mViewList != null && mViewList.add(v);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public int getCount() {
        return mViewList.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if(position >= mViewList.size()) {
            if (object instanceof ImageView) {
                ((ImageView) object).setImageBitmap(null);
                container.removeView((ImageView) object);
            }
            return;
        }
        View v = mViewList.get(position);
        if (v instanceof ImageView && imgUrlList != null) {//如果imgUrlList为null，没办法重新渲染,所以不能释放bitmap
            ((ImageView) v).setImageBitmap(null);
        }
        container.removeView(v);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View v = mViewList.get(position);
        if (v instanceof ImageView && imgUrlList != null) {
            if(position >= imgUrlList.size())
                position = position%imgUrlList.size();
            //2017.04.04 配置三个轮训会数组越界,需要求余
            String imgUrl = imgUrlList.get(position).getImageUrl();
            if (!TextUtils.isEmpty(imgUrl)) {
                ImageLoader.getInstance().displayImage(imgUrl, (ImageView) v);
            }
        }
        if(v.getParent() != null) {
            ((ViewGroup)v.getParent()).removeView(v);
        }
        container.addView(v);
        return v;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "";
    }
}
